package com.bridgeQQ.client.control
{
	import com.bridgeQQ.client.core.alive.IAlive;
	import com.bridgeQQ.client.core.client.IPeerClient;
	import com.bridgeQQ.client.model.BridgeModel;
	import com.bridgeQQ.client.util.ModelUtil;
	import com.bridgeQQ.client.vo.FriendType;
	import com.bridgeQQ.client.vo.User;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	
	public class ALiveClient implements IAlive
	{
		private var peerClient:IPeerClient;
		
		public function ALiveClient()
		{
			peerClient = ApplicationController.controller.getSubController("peerClient");
			peerClient.registerHandler("receiveAlive", receiveAlive);	
			
			BindingUtils.bindSetter(possessChanged, BridgeModel.instance, "possess");
		}
		
		private function possessChanged(possess:Object):void
		{
			if(possess != null)
			{
				notifyAlive();
			}
		}
		
		public function notifyAlive():void
		{
			if(!BridgeModel.instance.possess)
			{
				return;
			}
			var types:ArrayCollection = BridgeModel.instance.possess.friendTypes;
			var self:String = BridgeModel.instance.user.email;
			for(var i:int = types.length - 1; i >= 0; i--)
			{
				var type:FriendType = types.getItemAt(i) as FriendType;
				if(type == null)
				{
					continue;
				}		
				var friends:ArrayCollection = type.friends;		
				for(var k:int = friends.length - 1; k >= 0; k--)
				{
					var friend:User = friends.getItemAt(k) as User;
					if(friend != null && friend.peerID && friend.email != self)
					{
						peerClient.send(friend.peerID, "receiveAlive", self);
					}
				}
			}
		}
		
		public function receiveAlive(peerID:String, ...params):void
		{
			//Alert.show("receiveAlive: " + peerID);
			var userID:String = params[0];
			var user:User = ModelUtil.getFriend(BridgeModel.instance.possess, "email", userID);
			var type:FriendType = ModelUtil.getFriendTypeByUser(BridgeModel.instance.possess, userID);
			if(user != null && user.peerID != peerID)
			{
				user.peerID = peerID;
				if(type != null)
				{
                    type.friends.refresh();
				}
			}	
		}
		
		public function disConnected(peerID:String):void
		{
			var user:User = ModelUtil.getFriend(BridgeModel.instance.possess, "peerID", peerID);
			if(user == null)
			{
				return;
			}
			var type:FriendType = ModelUtil.getFriendTypeByUser(BridgeModel.instance.possess, user.email);
			if(user != null && user.peerID != null)
			{
				user.peerID = null;
				if(type != null)
				{
                    type.friends.refresh();
				}
			}	
		}
	}
}